package com.example.springbootdemo.controller;

import com.example.springbootdemo.properties.MeConfigInfo;
import com.example.springbootdemo.entity.Student;
import com.example.springbootdemo.repository.StudentRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 类描述：HelloWorld
 * Created by apk2sf on 2017/12/27.
 * email: apk2sf@163.com
 * QQ：337081267
 */
@RestController
//@Controller
@RequestMapping("/hellController")
public class HelloController {

    //获取配置文件中的自定义配置的属性
    @Value("${defaultUsername}")
    private String defaultUsername;

    @Autowired
    private MeConfigInfo mMeConfigInfo;

    @GetMapping
    //@RequestMapping(value = "/say/{id}", method = RequestMethod.GET)
    //public String say(@PathVariable("id") Integer id) {
    @RequestMapping(value = "/say", method = RequestMethod.GET)
    public String say(@RequestParam(value = "id", required = false, defaultValue = "12") Integer id) {
        System.out.println(id);
        System.out.println(defaultUsername);
        System.out.println(mMeConfigInfo);

        return "Hello Controller";
        //return "index";
    }


    @Autowired
    private StudentRepository mStudentRepository;

    @GetMapping("/stus")
    public List<Student> getAll() {
        return mStudentRepository.findAll();
    }

    @PostMapping("/stus")
    public Student insert(Student student, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            //有错误
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }

        return mStudentRepository.save(student);
    }
    @GetMapping("/delstu")
    public void insert(@RequestParam("id") Integer id) {
        mStudentRepository.delete(id);
    }
    @GetMapping("/findallbyage")
    public List<Student> findAllByAge(@RequestParam("age") Integer age) {
      return  mStudentRepository.findAllByAge(age);
    }

}